<?php
/* explain:		news system
 * Project:     
 * File:        news.php
 *
 * @ link 		http://www.../modules/
 * @ Email		ldmmyx@hotmail.com
 * @ copyright 	2005  Ling Deming
 * @ author 	ivan.ling  Ling Deming
 * @ version 	1.0
 *
 */
include_once("utils/CommonUtils.php");
include_once("domain/CategoryDomain.php");
include_once("dao/CommonDAO.php");
include_once("dao/CategoryDAO.php");
class CategoryImpl extends CommonUtils implements CategoryDAO, CommonDAO
{
	function __construct($DBTag)
	{
		parent::__construct();
		
		$this->DBTag = $DBTag;
		
	}

	/* get data via ID
	 *
	 * @param  int    id
	 * @return mixed  false:
	 */
	public function getById($id)
	{
		$sql  = 'SELECT id, parentId, name, title, descript, r_couponCount, isLeaf, status ';
		$sql .= "FROM category WHERE id = $id";
		
		$conn = null;
		$oCat = null;
		try {
			$conn 	= $this->getConnection($this->DBTag);
			$rs 	= mysql_query($sql, $conn);
			
			if ($row = mysql_fetch_row($rs)) {
				$oCat = new CategoryDomain();

				$oCat->setId($row[0]);
				$oCat->setParentId($row[1]);
				$oCat->setName($row[2]);
				$oCat->setTitle($row[3]);
				$oCat->setDescript(strip_tags($row[4]));
				$oCat->setCouponCount($row[5]);
				$oCat->isLeaf = $row[6];
				$oCat->status = $row[7];
			} else {
				$this->messages = "get coupon data failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($conn);
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();
		}

		$this->freeConnection($this->DBTag, $conn);
		
		return $oCat;
	}

/* get data via ID
	 *
	 * @param  int    id
	 * @return mixed  false:
	 */
	public function getByName($name)
	{
		$sql  = 'SELECT id, parentId, name, title, descript, r_couponCount, isLeaf, status ';
		$sql .= "FROM category WHERE name = '$name'";
		
		$oCat = null;
		$conn = null;
		
		try {
			$conn 	= $this->getConnection($this->DBTag);
			$rs 	= mysql_query($sql, $conn);
			
			if ($rs && $row = mysql_fetch_row($rs)) {
				$oCat = new CategoryDomain();

				$oCat->setId($row[0]);
				$oCat->setParentId($row[1]);
				$oCat->setName($row[2]);
				$oCat->setTitle($row[3]);
				$oCat->setDescript(strip_tags($row[4]));
				$oCat->setCouponCount($row[5]);
				$oCat->isLeaf = $row[6];
				$oCat->status = $row[7];
			} else {
				$this->messages = "get coupon data failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($conn);
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

		}
		
		if($conn != null)
			$this->freeConnection($this->DBTag, $conn);
		
		return $oCat;
	}

	public function getByCouponId($couponId)
	{
		$sql  = 'SELECT c.id, c.parentId, c.name, c.title, c.descript, c.r_couponCount, isLeaf, status ';
		$sql .= "FROM category c, coupon_category cc WHERE c.id = cc.categoryId AND cc.couponId = $couponId LIMIT 1";
		
		$oCat = null;
		$conn = null;
		
		try {
			$conn 	= $this->getConnection($this->DBTag);
			$rs 	= mysql_query($sql, $conn);
			
			if ($rs && $row = mysql_fetch_row($rs)) {
				$oCat = new CategoryDomain();

				$oCat->setId($row[0]);
				$oCat->setParentId($row[1]);
				$oCat->setName($row[2]);
				$oCat->setTitle($row[3]);
				$oCat->setDescript(strip_tags($row[4]));
				$oCat->setCouponCount($row[5]);
				$oCat->isLeaf = $row[6];
				$oCat->status = $row[7];
				
			} else {
				$this->messages = "get coupon data failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($conn);
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();
		}
		
		$this->freeConnection($this->DBTag, $conn);
		
		return $oCat;
	}
	
	public function add($oCat)
	{
		
		if($oCat instanceof CategoryDomain){			
			$sql 	 = "INSERT INTO category SET parentId=";
			$sql	.= $oCat->parentId;
			
			$sql 	.= ", name='";
			$sql	.= addslashes($oCat->name);
	
			$sql 	.= "', title='";
			$sql	.= addslashes($oCat->title);
	
			$sql 	.= "', descript='";
			$sql	.= addslashes($oCat->descript);

			$sql	.= "', status=";
			$sql	.= $oCat->status;
			
			$sql	.= ", isLeaf=";
			$sql	.= $oCat->isLeaf;
			
			$id = $this->insert($this->DBTag, $sql);
			
			$oCat->setId($id);
		}else{
			$id	= -1;
			
			$this->message = 'input object is not instance of CategoryDomain.';
		}
			
		return $id;
	}
  	
	/* edit
	 *
	 * @param  string 	userid		news class name 
	 * @param  string 	number		man number  
	 * @param  string  	position    position
	 * @param  string 	summary		summary 
	 * @param  string 	descript	descript  
	 * @param  datetime	startDate	start date
	 * @param  datetime endDate		end date
 	 	 * @param  return 	boolean
	 */
	public function edit($oCat)
	{
		$parentId 	= $oCat->parentId;
		$name		= addslashes($oCat->name);
		$title		= addslashes($oCat->title);
		$descript	= addslashes($oCat->descript);
		$isLeaf		= $oCat->isLeaf;
		$id			= $oCat->id;
		$status		= $oCat->status;
		
		$sql = "UPDATE category SET parentId='$parentId', name='$name', title = '$title', descript = '$descript', isLeaf = '$isLeaf', status='$status'  WHERE id = $id ";
		$rs	 = $this->update($this->DBTag, $sql);
		if($rs)
			return true;
		else
			return false;
	}
	
	/* delete news class
	 *
	 * @param  int    	id
	 * @param  string  	status
	 * @param  return 	boolean
	 */
	public function delete($id)
	{
		$sql = "DELETE FROM category WHERE id = $id";
		$rs	 = $this->update($this->DBTag, $sql);
		if($rs)
			return true;
		else
			return false;
	}
	
	public function getCatogories($page = 0, $discount = 20)
	{
		return $this->getCustoms(" WHERE status = 1 AND parentId = 0 AND r_couponCount > 0", " order by r_order", $page, $discount);
	}
	
	/* list
	 *
	 * @ param  string 	class id
	 * @ param  string 	page
	 * @ param  string 	discount
	 * @ param  string 	url
	 * @ param  return 	array
	 */
	public function getCustoms($where, $order, $page = 0, $discount = 20)
	{
		$arrback 	= array();
		$conn		= null;
		
		try{
			$conn 	= $this->getConnection($this->DBTag);
			
			$sql 	= "SELECT count(1) FROM category $where";
			$rs  	= mysql_query($sql, $conn);
			
			list($total) = mysql_fetch_row($rs);
			
			$this->mutilPager($total, $page, $discount);
			
			if(!empty($total)){
				$sql  = 'SELECT id, parentId, name, title, descript, r_couponCount, isLeaf, status';
				$sql .= " FROM category  $where $order";
				$sql .= " LIMIT $this->firstcount, $discount";
				
				$rs  = mysql_query($sql, $conn);
				if($rs){
					while($row = mysql_fetch_array($rs)){
						$oCat = new CategoryDomain();

						$oCat->setId($row[0]);
						$oCat->setParentId($row[1]);
						$oCat->setName($row[2]);
						$oCat->setTitle($row[3]);
						$oCat->setDescript(strip_tags($row[4]));
						$oCat->setCouponCount($row[5]);
						$oCat->isLeaf = $row[6];
						$oCat->status = $row[7];
						
						$arrback[] = $oCat;
					}
				}else {
					$this->message = "select failed. sql : $sql";
					$this->message .= "<br>error: " . mysql_error($conn);

				}
			}
		}catch(Exception $e){
			$this->message = $e->getMessage();			
		}
		
		$this->freeConnection($this->DBTag, $conn);
		
		return $arrback;
	}
	
	public function getTopTree($categoryId = 0)
	{	
		$topCatId = $this->getTopDirId($categoryId);
		
		return $this->getCategoryTree($topCatId);
	}
	
	public function getTopDirId($categoryId)
	{
		if($categoryId < 1)
			return $categoryId;
		
		while(true){
			$oCat = $this->getById($categoryId);
			if(is_object($oCat)){
				if($oCat->getParentId() > 0)
					$categoryId = $oCat->getParentId();
				else
					break;
			}else
				break;
		}
		
		return $categoryId;
	}
	
	public function getCategoryTree($categoryId)
	{
		$arrTmpStack 	= array();
		$arrLevelStack 	= array();
		$arrCategories 	= array();
		
		$i = 1;
		if($categoryId < 1){
//			$arrSubCategories = $this->getCustoms(" WHERE r_couponCount > 0 AND parentid = 0", ' ORDER BY name', 0, 1000);			
			$arrSubCategories = $this->getCustoms(" WHERE parentid = 0", ' ORDER BY name', 0, 1000);	
			
			foreach($arrSubCategories as $subCategory){
				array_push($arrTmpStack, $subCategory);
				array_push($arrLevelStack, $i);
				
				$arrCategories[] = $subCategory;	
			}
		}else{
			$oTopCat = $this->getById($categoryId);

			array_push($arrTmpStack, $oTopCat);
			array_push($arrLevelStack, $i);
			
			$arrCategories[] = $oTopCat;		
		}		
		
		while(sizeof($arrTmpStack) > 0){
			$oCat 	= array_pop($arrTmpStack);
			$i 		= array_pop($arrLevelStack);
			
			$oCat->setLevel($i);
			
			$arrSubCategories = $this->getCustoms(" WHERE r_couponCount > 0 AND parentid=" . $oCat->getId(), ' ORDER BY name', 0, 1000);
			
			$i++;
			foreach($arrSubCategories as $subCategory){
				array_push($arrTmpStack, $subCategory);
				array_push($arrLevelStack, $i);
				
				$oCat->addSubCategory($subCategory);
			}
		}		
		
		return $arrCategories;
	}
	
	public function getCategoryCouponCount($categoryId)
	{
		if($categoryId < 1)
			return 0;
		
		$couponCount	= 0;
		
		$arrTmpStack 	= array();
		$arrLevelStack 	= array();
		
		$i = 1;
		
		$oTopCat = $this->getById($categoryId);
		$couponCount = $oTopCat->getCouponCount();

		array_push($arrTmpStack, $oTopCat);
		array_push($arrLevelStack, $i);
		
		while(sizeof($arrTmpStack) > 0){
			$oCat 	= array_pop($arrTmpStack);
			$i 		= array_pop($arrLevelStack);
			
			$oCat->setLevel($i);
			
			$arrSubCategories = $this->getCustoms(" WHERE r_couponCount > 0 AND parentid=" . $oCat->getId(), '', 0, 1000);
			
			$i++;
			foreach($arrSubCategories as $subCategory){
				array_push($arrTmpStack, $subCategory);
				array_push($arrLevelStack, $i);
				
				$oCat->addSubCategory($subCategory);
				$couponCount += $subCategory->getCouponCount();
			}
		}
		
		
		return $couponCount;
	}
	
	public function getLeafIds($parentid, $isIncludeParent = false)
	{
		$arrParentid 	= array();
		$arrTmpStack 	= array();
		$arrLevelStack 	= array();
		$arrClassid		= array();
		
		$i = 0;
		array_push($arrTmpStack, $parentid);
		
		$conn 	= $this->getConnection($this->DBTag);
		
		while(sizeof($arrTmpStack) > 0){
			$strtmp = array_pop($arrTmpStack);
			$i 		= array_pop($arrLevelStack);
			if($strtmp > 0){
				$sql = "SELECT isLeaf FROM category WHERE id = $strtmp";
				
				$rs  = mysql_query($sql, $conn);
				if($rs){
					$arrback = mysql_fetch_array($rs);
					
					if($arrback['isLeaf'] == 1 && ($isIncludeParent && $strtmp == $parentid || $strtmp != $parentid))
						array_push($arrClassid, $strtmp);
				}
			}
		
		
			$sql = "SELECT id FROM category WHERE parentid=$strtmp";
			
	        $rs  = mysql_query($sql, $conn);
			if($rs){
				$mixBack = array();
				
				while($arrCache = mysql_fetch_array($rs)){
					$mixBack[] = $arrCache;
				}
				
				$i++;
				foreach($mixBack as $value){
					array_push($arrTmpStack,$value['id']);
					array_push($arrLevelStack,$i);
				}
			}
		}
		
		$this->freeConnection($this->DBTag, $conn);
		
		return $arrClassid;
	}
	
	public function getLeafIdsStr($parentid, $isIncludeParent = false, $glue = ',')
	{
		$arrLeafIds = $this->getLeafIds($parentid, $isIncludeParent);
		
		return implode($glue, $arrLeafIds);
	}
	
	public function getCouponCount()
	{
		$sql  = 'SELECT ct.categoryId, COUNT(1) FROM coupon c, coupon_category ct WHERE ct.couponId = c.id AND c.status = 1 GROUP BY ct.categoryId';
			
		return $this->getHash($this->DBTag, $sql);
	}
	
	public function getHasCoupons()
	{
		$sql  = 'SELECT id, r_couponCount FROM category WHERE status = 1 AND r_couponCount > 0';
			
		return $this->getHash($this->DBTag, $sql);
	}
	
	
	public function getCategoryIdByAlias($alias)
	{
		$sql  = "SELECT categoryId FROM category_alias WHERE alias = '" . addslashes($alias) . "'";
		
		$catId = $this->getColumn($this->DBTag, $sql);
		 
		return $catId;
	}
	
	public function getCategoryByAlias($alias)
	{
		$categoryId = $this->getCategoryIdByAlias($alias);

		if(!empty($categoryId)){			
			return $this->getById($categoryId);
		}else{
			return false;
		}
	}
	
	public function getMessage() 
	{
		return $this->message;
	}
	
}
?>
